package cn.topcodes.tcsf.wechat.web.controller;

import cn.topcode.unicorn.wxsdk.WXContext;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.wechat.domain.entity.WechatKfAccount;
import cn.topcodes.tcsf.wechat.domain.entity.WechatMessage;
import cn.topcodes.tcsf.wechat.domain.entity.WechatMp;
import cn.topcodes.tcsf.wechat.domain.entity.WechatUser;
import cn.topcodes.tcsf.wechat.domain.vo.WechatMessageVo;
import cn.topcodes.tcsf.wechat.domain.form.WechatMessageForm;
import cn.topcodes.tcsf.wechat.service.WechatKfAccountService;
import cn.topcodes.tcsf.wechat.service.WechatMpService;
import cn.topcodes.tcsf.wechat.service.WechatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 微信消息管理控制器
 * @author unicorn
 * @date 2017-08-17 15:51:48
 */
@Controller
@RequestMapping("/admin/wechat/message")
public class WechatMessageController extends AdminController<WechatMessage,WechatMessageVo,WechatMessageForm> {

	@Autowired
	private WechatMpService wechatMpService;

	@Autowired
	private WechatKfAccountService wechatKfAccountService;

	@Autowired
	private WechatUserService wechatUserService;

	@Override
	protected String getPageFolder() {
		return "wechat/admin/message";
	}

	@Override
	public String update(@RequestParam Long id, HttpServletRequest request, Model model) {
		List<WechatKfAccount> accountList = this.wechatKfAccountService.findAll();
		model.addAttribute("kfAccounts", accountList);
		return super.update(id, request, model);
	}

	@Override
	protected List<WechatMessageVo> entity2Vo(List<WechatMessage> entitys, HttpServletRequest request) {
		List<WechatMessageVo> list = super.entity2Vo(entitys, request);
		Long wechatMpId = Long.parseLong(request.getParameter("search_EQL_wechatMpId"));
		WechatMp wechatMp = wechatMpService.findOne(wechatMpId);
		for(WechatMessageVo vo : list) {
			vo.setToken(wechatMp.getToken());
			WechatUser wechatUser = wechatUserService.findByOpenId(vo.getFromUserName());
			if(wechatUser != null) {
				vo.setFromNickname(wechatUser.getNickname());
				vo.setFromWechatUserId(wechatUser.getId());
			}
		}
		return list;
	}
}
